package controller

import (
	"github.com/RaymondCode/simple-demo/DB"
	"github.com/RaymondCode/simple-demo/DB/table"
	"github.com/gin-gonic/gin"
	"net/http"
)

// usersLoginInfo use map to store user info, and key is username+password for demo
// user data will be cleared every time the server starts
// test data: username=zhanglei, password=douyin
var usersLoginInfo = map[string]User{
	"zhangleidouyin": {
		Id:            1,
		Name:          "zhanglei",
		FollowCount:   10,
		FollowerCount: 5,
		IsFollow:      true,
	},
}

var userIdSequence = int64(1)

type UserLoginResponse struct {
	Response
	UserId int64  `json:"user_id,omitempty"`
	Token  string `json:"token"`
}

type UserResponse struct {
	Response
	User []User `json:"user"`
}

func Register(c *gin.Context) {
	username := c.Query("username")
	password := c.Query("password")

	token := username + password
	tokens := make([]string, 100)
	db := DB.Init()
	db.Select("token").Find(&tokens)
	var exist bool
	for _, index := range tokens {
		if index == token {
			exist = true
		}
	}
	if exist == true {
		c.JSON(http.StatusOK, UserLoginResponse{
			Response: Response{StatusCode: 1, StatusMsg: "User already exist"},
		})
	} else {
		users := &table.User{Name: username, Password: password, Token: token}
		db.Create(users)
		c.JSON(http.StatusOK, UserLoginResponse{
			Response: Response{StatusCode: 0},
			UserId:   int64(users.ID),
			Token:    username + password,
		})
	}
}

func Login(c *gin.Context) {
	username := c.Query("username")
	password := c.Query("password")

	token := username + password

	tokens := make([]string, 100)
	db := DB.Init()
	db.Select("token").Find(&tokens)
	var exist bool
	for _, index := range tokens {
		if index == token {
			exist = true
		}
	}
	if exist == true {
		var UserId table.User
		db.Where("token = ?", token).Find(&UserId)
		c.JSON(http.StatusOK, UserLoginResponse{
			Response: Response{StatusCode: 0},
			UserId:   int64(UserId.ID),
			Token:    token,
		})
	} else {
		c.JSON(http.StatusOK, UserLoginResponse{
			Response: Response{StatusCode: 1, StatusMsg: "User doesn't exist"},
		})
	}
}

func UserInfo(c *gin.Context) {
	token := c.Query("token")

	db := DB.Init()
	var users []User
	var user table.User
	db.Model(&user).Where("token = ?", token).Find(&users)

	if users != nil {
		c.JSON(http.StatusOK, UserResponse{
			Response: Response{StatusCode: 0},
			User:     users,
		})
	} else {
		c.JSON(http.StatusOK, UserResponse{
			Response: Response{StatusCode: 1, StatusMsg: "User doesn't exist"},
		})
	}
}
